import winreg
import os
import re
import json
import requests
# !C:\Python37 python
# -*- coding: utf-8 -*-
# @Time    : 2020/8/25 8:26
# @File    : douyin_v2.py


class DY:
    def __init__(self):
        self.headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3904.108 Safari/537.36'}
        self.android_headers = {'user-agent': 'Android'}

    # 获取windows桌面路径
    def get_desktop(self):
        key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                             r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
        return winreg.QueryValueEx(key, "Desktop")[0]

    # 去除视频名称中的非法字符，以便保存视频。
    def validateTitle(self, title):
        rstr = r"[\/\\\:\*\?\"\<\>\|]"  # '/ \ : * ? " < > |'
        new_title = str.replace(
            re.sub(rstr, "_", title), ' ', '')  # 替换为下划线并过滤空格
        return new_title

    def get_share_url(self, url):
        response = requests.get(
            url, headers=self.headers, allow_redirects=False)
        if 'location' in response.headers.keys():
            return response.headers['location']
        else:
            raise Exception("解析失败")
        pass

    # 获取视频下载地址，并下载视频
    def get_data(self, url):
        response = requests.get(url, headers=self.headers).text
        json_str = json.loads(response)
        video_title = json_str.get("item_list")[0].get(
            "share_info").get("share_title")
        video_name = self.validateTitle(video_title)
        download_url = json_str['item_list'][0]['video']['play_addr']['url_list'][0].replace(
            "playwm", "play")
        with open(video_name + '.mp4', 'wb') as f:
            f.write(requests.get(url=download_url,
                                 headers=self.android_headers).content)
            pass
        print('视频下载完成!')
        pass

    # 解析用户输入的抖音分享链接
    def run(self):
        share = input("请输入你要去水印的抖音短视频链接：")
        url = re.findall(r'https://v.douyin.com/.*?/', share)[0]
        location = self.get_share_url(url)
        vid = re.findall(r'/share/video/(\d*)', location)[0]
        xhr_url = 'https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids={}'.format(
            vid)
        self.get_data(xhr_url)


if __name__ == '__main__':
    # 获取win桌面路径，用来将下载好的视频保存至桌面
    dy = DY()
    desktop = dy.get_desktop()
    os.chdir(desktop)
    dy.run()
